<?php

namespace app\admin\controller\work;

use app\common\controller\Backend;
use app\admin\model\WorkTemplate;
use app\admin\model\WorkTemplateItem;
use think\Session;
use app\admin\model\AuthGroupAccess;
use app\admin\model\Admin;
use think\Db;
/**
 * 浮动性工作模板提交管理
 *
 * @icon fa fa-circle-o
 */
class WorkTemplateLog extends Backend
{
    public $group;

    /**
     * WorkTemplateLog模型对象
     * @var \app\admin\model\WorkTemplateLog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WorkTemplateLog;
        $this->view->assign("type_arr", (new WorkTemplate)->type_arr);
        $this->view->assign("teacher_type_arr", $this->model->teacher_type_arr);
        // 查询当前用户权限
        $group = Db::table('b_auth_group_access a')
            ->field('g.*')
            ->join('b_auth_group g','g.id = a.group_id')
            ->where('a.uid',session('admin.id'))
            ->find();
        $this->group = $group;
        $this->assign('group',$group);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $AuthGroupAccessInfo = AuthGroupAccess::where('uid',$this->auth->id)->find();
            if(empty($AuthGroupAccessInfo))$this->error('登录错误');
            $and_where = [];
            if($AuthGroupAccessInfo['group_id'] == 12){
                $and_where['admin_id'] = $this->auth->id;
            }
            $group_info = $this->group;
            $list = $this->model
                    ->with(['admin','template'])
                    ->where($and_where)
                    ->where(function($query) use ($group_info,$limit){
                        if(!in_array($group_info['id'],[1,6,8])){ // 判断是否是超管 不限制所有都能查看
                            $query->where('work_template_log.admin_id',session('admin.id'));
                        }
                    })
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $first_trial_admin = Admin::where('id',$row->first_trial_admin_id)->field('nickname,signature')->find();
                $row->first_trial_admin_name = $first_trial_admin?$first_trial_admin['nickname']:'';
                $row->first_trial_admin_signature = $first_trial_admin?$first_trial_admin['signature']:'';

                $end_trial_admin = Admin::where('id',$row->end_trial_admin_id)->field('nickname,signature')->find();
                $row->end_trial_admin_name = $end_trial_admin?$end_trial_admin['nickname']:'';
                $row->end_trial_admin_signature = $end_trial_admin?$end_trial_admin['signature']:'';
                $row->visible(['id','admin_id','type','teacher_type','select_time','status','reject_reason',
                    'first_trial_reject_reason','first_trial_admin_name','first_trial_time',
                    'end_trial_reject_reason','end_trial_time','end_trial_admin_name','create_time','admin','template.name','first_trial_admin_signature','end_trial_admin_signature']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $temp_item_id = $params['temp_item_id'];
                    $temp_item_ids = $temp_item_id?explode(',',$temp_item_id):[];
                    foreach ($temp_item_ids as $id){



                        $params['temp_item_id'] = $id;
                        $handle_data =  $this->_handle_data($params);
                        if($handle_data['code'] != 1)exception($handle_data['msg']);

                        $temp_info = Db::name('work_template_log')->where(['temp_id'=>$params['temp_id'],'temp_item_id'=>$id])
                            ->whereIn('status',[1,2,3,5])->find();
                        if($temp_info){
                            $nickname = Admin::where('id',$temp_info['admin_id'])->value('nickname');
                            exception('此条数据与“'.$nickname.'”老师提交数据冲突，冲突数据ID为“'.$temp_info['id'].'”');
                        }
                        $params = $handle_data['data'];
                        $result = $this->model->allowField(true)->insert($params);
                    }
                    if(!$result)exception('添加失败');
                    Db::commit();
                } catch (\Throwable $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $handle_data =  $this->_handle_data($params);
                    if($handle_data['code'] != 1)exception($handle_data['msg']);
                    $params = $handle_data['data'];
                    $result = $row->allowField(true)->save($params);
                    if(!$result)exception('编辑失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 提交审核
     */
    public function to_examine($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $res = $row->save(array('status'=>'2'));
                if (!$res)exception('提交成功');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = explode(',',$ids);
            try {
                $this->model->whereIn('id',$ids )->delete();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function _handle_data($params)
    {
        try{
            if($params['type'] != 3){//非社团删除主教/助教值
                unset($params['teacher_type']);
            }else{
                if(empty($params['teacher_type']))exception('请选择主教/助教');
            }
            $temp_info = WorkTemplate::where('id',$params['temp_id'])->find();
            if(empty($temp_info))exception('该模板已被删除');
            $temp_item_info = WorkTemplateItem::where('id',$params['temp_item_id'])->find();
            if(empty($temp_item_info))exception('该模板时间已被删除');
            if($temp_item_info['status'] != 1 && $temp_item_info['grade_group'] != $this->auth->grade_group)exception('该模板时间您不能选择');
            $params['select_time'] = $temp_item_info['select_time'];
            $params['admin_id'] = $this->auth->id;
            return array('code'=>'1','msg'=>'ok','data'=>$params);
        }catch (\Throwable $e){
            return array('code'=>'0','msg'=>$e->getMessage());
        }

    }

}
